// pages/chat/chat.ts
const io = require('../../lib/weapp.socket.io.js');
import { axios } from "../../utils/request"
const socket =  io('wss://www.tinyxu.fun/',{
  transports: ['websocket'],
  reconnectionAttempts: 3, // 失败后重新连接次数，一直失败总共尝试四次
    reconnectionDelay: 2000, // 重新连接间隔时间毫秒
});
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo:Object,
    info:"",
    openId:"",
    skip:9,
    isEmpt:false,
    initData:[],
    scrollLast: ""
  },
  async init(){
    const initData = await axios('/chat/findAll',"GET",{
      skip:0,
      take:10
    }) as any
    this.setData({
      skip:9,
      initData:initData.data.data.reverse()
    })
  },
  send(){
    let info = this.data.info
    if(info){
      socket.emit("send",{
        info,
        ...this.data.userInfo,
       })
       this.setData({
         info:""
       })
    }else{
      wx.showToast({
        title:"消息不能为空",
        icon:"error"
      })
    }
  },
  getScollBottom() {
    console.log(`#item${this.data.initData.length}`);
    wx.pageScrollTo({
      selector: `#item${this.data.initData.length}`
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
   async onShow() {
    this.getTabBar().setData({
      active:2
    })
    const userInfo = wx.getStorageSync("userInfo")
    const openId = wx.getStorageSync("token")
    if(userInfo){
      this.setData({
        userInfo,
        openId
      })
      this.init()
      this.getScollBottom()
    }else{
      wx.navigateTo({
        url:'/pages/login/login'
      })
    }
    socket.on("send",(_:any)=>{
      this.init()
      this.getScollBottom()
    })
  },
  async onPullDownRefresh() {
    const {data} = await axios('/chat/count') as any
    const total = data.data
    if( this.data.initData.length <= total-5 ){
      this.setData({
        skip:this.data.skip+5
      })
      const res = await axios('/chat/findAll',"GET",{
        skip:this.data.skip,
        take:5
      }) as any
      const preData = res.data.data
      const initData = this.data.initData as any
      preData.forEach((item:any)=>{
        initData.unshift(item)
      })
      this.setData({
        initData
      })
      wx.stopPullDownRefresh();
    }else{
      wx.stopPullDownRefresh();
      this.setData({
          isEmpt:true
      })
    }
    wx.stopPullDownRefresh();
  },
})